package com.example.xu.crime;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.util.Size;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * A simple {@link Fragment} subclass.
 */
public class CrimeCameraFragment extends Fragment {
    private static final String TAG = "CrimeCameraFragment";
    private static int REQUEST_IMAGE_CAPTURE = 1;

    public static final String EXTRA_PHOTO_FILENAME = "crime_photo_filename";

    private Camera mCamera;
    private SurfaceView mSurfaceView;
    private SurfaceHolder mHolder;
    private View mProgressContainer;

    public CrimeCameraFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_crime_camera, container, false);

        Button takePictureButton = (Button)v.findViewById(R.id.crime_camera_takePictureButton);
        takePictureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                getActivity().finish();
                mCamera.takePicture(mShutterCallback, null, mJpegCallback);
            }
        });
        mProgressContainer = v.findViewById(R.id.progressBar);
        mProgressContainer.setVisibility(View.INVISIBLE);

        mSurfaceView = (SurfaceView)v.findViewById(R.id.crime_camera_sufaceView);
        mHolder = mSurfaceView.getHolder();

        mHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                try {
                      if (mCamera != null) {
                        mCamera.setPreviewDisplay(mHolder);
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Error setting up preview display", e);
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                if (mCamera == null) return;

                Camera.Parameters parameters = mCamera.getParameters();
                Size s = new Size(640,480);
                parameters.setPreviewSize(s.getWidth(), s.getHeight());
                mCamera.setParameters(parameters);
                try {
                    mCamera.startPreview();
                } catch (Exception e) {
                    Log.e(TAG, "Could not start preview", e);
                    mCamera.release();
                    mCamera = null;
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (mCamera != null) {
                    mCamera.stopPreview();
                }
            }
        });

        return v;
    }

    private Camera.ShutterCallback mShutterCallback = new Camera.ShutterCallback() {

        @Override
        public void onShutter() {
            mProgressContainer.setVisibility(View.VISIBLE);
        }
    };

    private Camera.PictureCallback mJpegCallback;

    {
        mJpegCallback = new Camera.PictureCallback() {

            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                String filename = UUID.randomUUID().toString() + ".jpg";
                FileOutputStream os = null;
                boolean success = true;

                try {
                    os = getActivity().openFileOutput(filename, Context.MODE_PRIVATE);
                    os.write(data);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e(TAG, "Error writing to file " + filename, e);
                    success = false;
                } finally {
                    try {
                        if (os != null)
                            os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e("TAG", "Error closing file " + filename, e);
                        success = false;
                    }
                }

                if (success) {
                    //Log.i(TAG, "JPEG saved at " + filename);
                    Intent i = new Intent();
                    i.putExtra(EXTRA_PHOTO_FILENAME, filename);
                    getActivity().setResult(Activity.RESULT_OK, i);
                } else {
                    getActivity().setResult(Activity.RESULT_CANCELED);
                }
                getActivity().finish();
            }
        };
    }

    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }

    private void releaseCameraAndPreview() {
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mCamera = getCameraInstance();
        Log.d(TAG, "Open camera onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        releaseCameraAndPreview();
    }
}
